package linearList;

import java.util.Iterator;

//顺序表
public class SequenceList<T> implements Iterable<T> {
    private int N;
    private T[] eles;
    /*public  SequenceList(int capacity){
    this.N=0;
    this.eles= (T[]) new Object[capacity];
    }*/
    //扩容后不需要在指定大小
    public  SequenceList(int capacity){
        this.N=0;
        this.eles= (T[]) new Object[capacity];
    }
    public void clear(){
        this.N = 0;
        this.eles=null;
    }
    public boolean isEmpty(){
        return N==0;
    }
    public int length(){
        return N;
    }
    //在i处素中插入
   public void insert(int i , T t){
        if (i < 0 || i >= N){
           throw new RuntimeException("索引越界");
        }
        if (N == eles.length &&  N >0 ){
            reSize(eles.length*2);
        }
        for (int index = N; index > i ; index--){
            eles[index] = eles[index-1];
        }
        eles[i] = t;
        N++;
    }
    public void insert(T t){
        if (N == eles.length &&  N >0 ){
            reSize(eles.length*2);
        }
        eles[N++] = t;
    }
    //删除i位置处的元素
    public T remove(int i ){
        if (i < 0 || i >= N){
            throw new RuntimeException("索引越界");
        }
        T tem = eles[i];
        for (int index = i ; index< N-1; index++){
            eles[index] = eles[index+1];
        }
        N--;
        if (N >0 && N<eles.length/4){
            reSize(eles.length/2);
        }
        return tem;
    }
    //返回元素首次出现的索引
    public int indexOf(T t){
        for (int i = 0; i <N ; i++){
            if (eles[i].equals(t)){
                return i;
            }
        }
        return -1;
    }
    //读取并返回元素的第i个值
    public T get(int i ){
        return eles[i];
    }

    @Override
    public Iterator<T> iterator() {
        return new ImIterator();
    }
    public class ImIterator implements Iterator{
       private int curr ;

        public ImIterator() {
            this.curr = 0;
        }

        @Override
        public boolean hasNext() {
            return curr < N;
        }

        @Override
        public Object next() {

            return eles[curr++];
        }
    }
    //扩容
    private void reSize(int newSize){
        T[] tem = eles;
        eles = (T[]) new Object[newSize];
        for (int i = 0 ; i <N; i++){
            eles[i] = tem[i];
        }

    }
}
